package com.ctshk.rpc.visa.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.constant.RedisConstants;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.*;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.service.support.BaseService;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.booking.enums.SupplierReserveTypeEnum;
import com.ctshk.rpc.booking.req.system.visa.add.SupplierOrderSystemVisaAddReq;
import com.ctshk.rpc.booking.req.system.visa.add.SupplierSystemOrderVisaAddReq;
import com.ctshk.rpc.booking.req.system.visa.add.SupplierSystemOrderVisaDetailAddReq;
import com.ctshk.rpc.booking.service.ISupplierOrderService;
import com.ctshk.rpc.finance.json.FileJson;
import com.ctshk.rpc.finance.req.bill.BillAddCollectionReq;
import com.ctshk.rpc.finance.req.bill.BillAddRefundReq;
import com.ctshk.rpc.finance.service.IFinanceBillService;
import com.ctshk.rpc.payment.enums.PayCurrency;
import com.ctshk.rpc.system.dto.MainDataCurrencyListDTO;
import com.ctshk.rpc.system.dto.MainDataCurrencyQueryDTO;
import com.ctshk.rpc.system.dto.SysDepartmentDTO;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.req.MainDataCurrencyListReq;
import com.ctshk.rpc.system.req.MainDataCurrencyUpdateStatusReq;
import com.ctshk.rpc.system.service.IMainDataCurrencyService;
import com.ctshk.rpc.system.service.ISysDepartmentService;
import com.ctshk.rpc.system.service.ISysSupplierService;
import com.ctshk.rpc.system.service.ISysUserService;
import com.ctshk.rpc.visa.dto.visa.VisaOrderInfoResp;
import com.ctshk.rpc.visa.dto.visa.VisaOrderListDTO;
import com.ctshk.rpc.visa.entity.*;
import com.ctshk.rpc.visa.mapper.*;
import com.ctshk.rpc.visa.req.visa.*;
import com.ctshk.rpc.visa.service.IVisaOrderService;
import com.ctshk.rpc.workflow.dto.ApprovalCheckDTO;
import com.ctshk.rpc.workflow.dto.ApprovalStartDTO;
import com.ctshk.rpc.workflow.service.ISysApprovalService;
import com.github.kfcfans.powerjob.client.OhMyClient;
import com.github.kfcfans.powerjob.common.response.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 签证订单 服务实现类
 * </p>
 *
 * @author 谢诗宏
 * @since 2021-01-28
 */
@Slf4j
@DubboService
public class VisaOrderServiceImpl extends ServiceImpl<VisaOrderMapper, VisaOrder> implements IVisaOrderService, BaseService {
    @Autowired
    private VisaMapper visaMapper;
    @Autowired
    private VisaTypeMapper visaTypeMapper;
    @Autowired
    private VisaProductMapper visaProductMapper;
    @Autowired
    private VisaOrderMapper visaOrderMapper;
    @Autowired
    private VisaOrderCollectionMapper visaOrderCollectionMapper;
    @DubboReference
    private ISysUserService iSysUserService;
    @Autowired
    private VisaOrderTouristMapper visaOrderTouristMapper;
    @Autowired
    private VisaManageMapper visaManageMapper;
    @Autowired
    private VisaOrderRefundMapper visaOrderRefundMapper;
    @DubboReference
    private IMainDataCurrencyService iMainDataCurrencyService;

    @DubboReference
    private ISupplierOrderService supplierOrderService;

    @DubboReference
    private ISysSupplierService sysSupplierService;

    @Override
    public Result<Void> supplieConfirmOrder(VisaOrderSupplieConfirmReq req, Long userId) {
        validateArgs(req);
        VisaOrder visaOrder = visaOrderMapper.assertExistSelectOneByKey("order_number", req.getSaleNumber());
        fillUpdateEntityUserId(visaOrder, userId);
        visaOrder.setBookingStatus(req.getReserveStatus());
        visaOrderMapper.assertUpdateById(visaOrder);

        return newResult();
    }

    /**
     * 订单中心签证列表
     *
     * @param visaOrderListReq
     * @return
     */
    @Override
    public PageResponse<VisaOrderListDTO> list(VisaOrderListReq visaOrderListReq) {
        IPage<VisaOrder> visaOrderIPage = null;
        // 分页条件查询
        QueryWrapper<VisaOrder> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(visaOrderListReq.getOrderNumber()), "order_number", visaOrderListReq.getOrderNumber());
        wrapper.eq(StringUtils.isNotBlank(visaOrderListReq.getVisaTypeId()), "visa_type_id", visaOrderListReq.getVisaTypeId());
        wrapper.eq(StringUtils.isNotBlank(visaOrderListReq.getStatus()), "status", visaOrderListReq.getStatus());
        wrapper.eq(StringUtils.isNotBlank(visaOrderListReq.getBookingStatus()), "booking_status", visaOrderListReq.getBookingStatus());
        wrapper.eq(StringUtils.isNotBlank(visaOrderListReq.getCancelStatus()), "cancel_status", visaOrderListReq.getCancelStatus());
        wrapper.eq(StringUtils.isNotBlank(visaOrderListReq.getSource()), "source", visaOrderListReq.getSource());
        wrapper.orderByDesc("gmt_create");
        if (StringUtils.isNotBlank(visaOrderListReq.getBeginDate())) {
//            wrapper.gt("gmt_create",visaOrderListReq.getBeginDate());
            wrapper.ge("gmt_create", visaOrderListReq.getBeginDate());
        }
        if (StringUtils.isNotBlank(visaOrderListReq.getEndDate())) {
//            wrapper.ge("gmt_create",visaOrderListReq.getEndDate());
            wrapper.le("gmt_create", visaOrderListReq.getEndDate());
        }
        wrapper.like(StringUtils.isNotBlank(visaOrderListReq.getContactName()), "contact_name", visaOrderListReq.getContactName());
        wrapper.eq(StringUtils.isNotBlank(visaOrderListReq.getCreateId()), "create_id", visaOrderListReq.getCreateId());
        if (StringUtils.isNotBlank(visaOrderListReq.getName())) {
            QueryWrapper<Visa> visaQueryWrapper = new QueryWrapper<>();
            visaQueryWrapper.like("name", visaOrderListReq.getName());
            visaQueryWrapper.eq("is_deleted", 0);
            visaQueryWrapper.eq("status", 0);
            List<Visa> visaList = visaMapper.selectList(visaQueryWrapper);
            if (visaList != null && visaList.size() > 0) {
                List<Long> idS = new ArrayList<>();
                for (Visa visa : visaList) {
                    idS.add(visa.getId());
                }
                QueryWrapper<VisaProduct> visaProductQueryWrapper = new QueryWrapper<>();
                visaProductQueryWrapper.in("visa_id", idS);
                visaProductQueryWrapper.eq("status", 0);
                List<VisaProduct> visaProductList = visaProductMapper.selectList(visaProductQueryWrapper);
                if (visaProductList != null && visaProductList.size() > 0) {
                    List<Long> productId = new ArrayList<>();
                    for (VisaProduct visaProduct : visaProductList) {
                        productId.add(visaProduct.getId());
                    }
                    wrapper.in("product_id", productId);
                }
            }
        }
        Page<VisaOrder> iPage = new Page<>(visaOrderListReq.getPageNo(), visaOrderListReq.getPageSize());
        visaOrderIPage = visaOrderMapper.selectPage(iPage, wrapper);
        if (CollectionUtils.isEmpty(visaOrderIPage.getRecords())) {
            return PageResponse.empty(visaOrderIPage.getCurrent());
        }
        List<VisaOrderListDTO> visaOrderListDTOList = new ArrayList<>();
        visaOrderIPage.getRecords().forEach(visaOrder -> {
            VisaOrderListDTO visaOrderListDTO = EntityUtil.copy(visaOrder, VisaOrderListDTO.class);
            if (null != visaOrder.getStatus()) {
                visaOrderListDTO.setStatus(visaOrder.getStatus());
            }
            QueryWrapper<VisaProduct> visaProductQueryWrapper = new QueryWrapper<>();
            //获取产品名称、国家
            if (visaOrder != null && visaOrder.getProductId() != null) {
                visaProductQueryWrapper.eq("status", 0);
                visaProductQueryWrapper.eq("id", visaOrder.getProductId());
                visaProductQueryWrapper.eq("is_deleted", 0);
                VisaProduct visaProduct = visaProductMapper.selectOne(visaProductQueryWrapper);
                if (visaProduct != null) {
                    QueryWrapper<Visa> visaQueryWrapper = new QueryWrapper<>();
                    visaQueryWrapper.eq("is_deleted", 0);
                    visaQueryWrapper.eq("status", 0);
                    visaQueryWrapper.eq("id", visaProduct.getVisaId());
                    Visa visa = visaMapper.selectOne(visaQueryWrapper);
                    if (visa != null) {
                        visaOrderListDTO.setName(visa.getName());
                        visaOrderListDTO.setCountryName(visa.getCountryName());
                        visaOrderListDTO.setVisaType(visa.getVisaType());
                        QueryWrapper<VisaType> visaTypeQueryWrapper = new QueryWrapper<>();
                        visaTypeQueryWrapper.eq("is_deleted", 0);
                        visaTypeQueryWrapper.eq("visa_id", visa.getId());
                        visaTypeQueryWrapper.eq("id", visaOrder.getTypeId());
                        VisaType visaType = visaTypeMapper.selectOne(visaTypeQueryWrapper);
                        if (visaType != null) {
                            visaOrderListDTO.setCurrency(visaType.getCurrency());
                        }
                    }
                }
            }
            if (visaOrder != null) {
                //todo   上线去掉
                UserDTO userDTO = null;
                try {
                    userDTO = iSysUserService.loadUserByParam(visaOrder.getCreateId(), 1);
                } catch (Exception e) {
                    throw new BusinessException(SystemError.SYS_502);
                }
                if (userDTO != null) {
                    visaOrderListDTO.setCreateName(userDTO.getCnSurname() + userDTO.getCnName() + "/" + userDTO.getDept());
                }
            }
            visaOrderListDTO.setSource(OrderSource.getOrderSourceName(1));
            visaOrderListDTOList.add(visaOrderListDTO);
        });
        PageResponse<VisaOrderListDTO> result = new PageResponse<>(visaOrderListDTOList, visaOrderIPage.getCurrent() == 1, visaOrderIPage.getTotal() <= (visaOrderIPage.getCurrent() * visaOrderIPage.getSize()), visaOrderIPage.getTotal(), visaOrderIPage.getCurrent(), visaOrderIPage.getSize());
        return result;
    }

    /**
     * 订单中心签证详情
     *
     * @param visaOrderInfoReq
     * @return
     */
    @Override
    public Result<VisaOrderInfoResp> query(VisaOrderInfoReq visaOrderInfoReq) {
        VisaOrderInfoResp visaOrderInfoResp = new VisaOrderInfoResp();
        //获取订单中心签证详情
        if (visaOrderInfoReq.getId() != null) {
            VisaOrder visaOrder = visaOrderMapper.selectById(visaOrderInfoReq.getId());
            if (visaOrder == null) {
                throw new BusinessException(SystemError.VISA_ORDER_25005);
            }
            visaOrderInfoResp = EntityUtil.copy(visaOrder, VisaOrderInfoResp.class);
            if (visaOrder.getStatus() != null && visaOrder.getBookingStatus() == null) {
                visaOrderInfoResp.setOrderStatus(visaOrder.getStatus());
            }
//            if (visaOrder.getStatus() != null && visaOrder.getBookingStatus() != null) {
//                if (visaOrder.getStatus() < visaOrder.getBookingStatus()) {
//                    visaOrderInfoResp.setOrderStatus(visaOrder.getStatus());
//                } else {
//                    visaOrderInfoResp.setOrderStatus(visaOrder.getBookingStatus());
//                }
//            }
            // 代付款、订单生成
            if (visaOrder.getBookingStatus() == 0 && visaOrder.getStatus() == 1 && visaOrder.getCancelStatus() == 0) {
                visaOrderInfoResp.setOrderStatus(1);
            }

            // 代付款、已取消
            if (visaOrder.getBookingStatus() == 0 && visaOrder.getStatus() == 3 && visaOrder.getCancelStatus() == 0) {
                visaOrderInfoResp.setOrderStatus(2);
            }

            // 已付款、待确认
            if (visaOrder.getBookingStatus() == 4 && visaOrder.getStatus() == 2 && visaOrder.getCancelStatus() == 0) {
                visaOrderInfoResp.setOrderStatus(3);
            }

            // 已付款、确认取消
            if (visaOrder.getBookingStatus() == 6 && visaOrder.getStatus() == 2 && visaOrder.getCancelStatus() == 0) {
                visaOrderInfoResp.setOrderStatus(4);
            }

            // 已付款、确认成功
            if (visaOrder.getBookingStatus() == 5 && visaOrder.getStatus() == 2 && visaOrder.getCancelStatus() == 0) {
                visaOrderInfoResp.setOrderStatus(5);
            }

//            if (visaOrder.getStatus() == 1) {
//                visaOrderInfoResp.setOrderStatus(1);
//                // 已付款
//            } else if (visaOrder.getStatus() == 2) {
//                // 已付款、待确认
//                if (visaOrder.getBookingStatus() == 4) {
//                    visaOrderInfoResp.setOrderStatus(2);
//                    // 已付款、确认成功
//                } else if (visaOrder.getBookingStatus() == 5) {
//                    visaOrderInfoResp.setOrderStatus(3);
//                    // 已付款、确认失败
//                } else if (visaOrder.getBookingStatus() == 6) {
//                    visaOrderInfoResp.setOrderStatus(4);
//                }
//                // 已取消
//            } else if (visaOrder.getStatus() == 3) {
//                if (visaOrder.getBookingStatus() == 4 || visaOrder.getBookingStatus() == 5 || visaOrder.getBookingStatus() == 6) {
//                    visaOrderInfoResp.setOrderStatus(5);
//                }
//            }
            if (visaOrder != null && visaOrder.getProductId() != null) {
                QueryWrapper<VisaProduct> visaProductQueryWrapper = new QueryWrapper<>();
                visaProductQueryWrapper.eq("status", 0);
                visaProductQueryWrapper.eq("id", visaOrder.getProductId());
                visaProductQueryWrapper.eq("is_deleted", 0);
                VisaProduct visaProduct = visaProductMapper.selectOne(visaProductQueryWrapper);
                if (visaProduct == null) {
                    throw new BusinessException(SystemError.VISA_ORDER_25012);
                }
                QueryWrapper<Visa> visaQueryWrapper = new QueryWrapper<>();
                visaQueryWrapper.eq("is_deleted", 0);
                visaQueryWrapper.eq("status", 0);
                visaQueryWrapper.eq("id", visaProduct.getVisaId());
                Visa visa = visaMapper.selectOne(visaQueryWrapper);
                if (visa == null) {
                    throw new BusinessException(SystemError.VISA_ORDER_25014);
                }
                visaOrderInfoResp.setName(visa.getName());
                visaOrderInfoResp.setCountryName(visa.getCountryName());
                visaOrderInfoResp.setHandleInstruction(visa.getHandleInstruction());
                QueryWrapper<VisaType> visaTypeQueryWrapper = new QueryWrapper<>();
                visaTypeQueryWrapper.eq("is_deleted", 0);
                visaTypeQueryWrapper.eq("visa_id", visa.getId());
                List<VisaType> visaTypeList = visaTypeMapper.selectList(visaTypeQueryWrapper);
                if (visaTypeList != null && visaTypeList.size() >= 1) {
                    VisaType visaType = visaTypeList.get(0);
                    MainDataCurrencyUpdateStatusReq req = new MainDataCurrencyUpdateStatusReq();
                    req.setId(visaType.getCurrencyId());
                    Result<MainDataCurrencyQueryDTO> query = iMainDataCurrencyService.query(req);
                    if (query.getData() != null) {
//                                visaType.setCurrency(query.getData().getCurrencyCode());
                        visaType.setCurrency(PayCurrency.HKD.getCode());
                    }
                    visaOrderInfoResp.setTypeName(visaType.getTypeName());
                    visaOrderInfoResp.setCurrency(visaType.getCurrency());
                }
            }
            //todo  上线去掉
            UserDTO userDTO = null;
            try {
                userDTO = iSysUserService.loadUserByParam(visaOrder.getCreateId(), 1);
            } catch (Exception e) {
                throw new BusinessException(SystemError.SYS_502);
            }
            if (userDTO != null) {
                visaOrderInfoResp.setCreateByName(userDTO.getCnSurname() + userDTO.getCnName() + "/" + userDTO.getDept());
            }
        }
        return Result.success(visaOrderInfoResp);
    }

    @DubboReference
    private ISysDepartmentService sysDepartmentService;

    @Value("${schedule.config.domain}")
    private String domain;

    @Value("${schedule.config.app-name}")
    private String appName;

    @Value("${schedule.config.password}")
    private String password;

    @Value("${schedule.job-id.order.visa}")
    private long jobId;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 预订中心签证申请
     *
     * @param visaHandleReq,user
     * @return
     */
    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public Long add(VisaHandleReq visaHandleReq, TokenUser user) {
        VisaOrder visaOrder = new VisaOrder();
        Long id = SnowflakeIdWorker.nextId();
        if (visaHandleReq.getId() != null) {
            QueryWrapper<VisaProduct> visaProductQueryWrapper = new QueryWrapper<>();
            visaProductQueryWrapper.eq("visa_id", visaHandleReq.getId());
            visaProductQueryWrapper.eq("status", 0);
            visaProductQueryWrapper.eq("is_deleted", 0);
            VisaProduct visaProduct = visaProductMapper.selectOne(visaProductQueryWrapper);
            if (visaProduct != null) {
                visaOrder.setProductId(visaProduct.getId());
            }
        }
        visaOrder.setId(id);
        visaOrder.setCreateId(user.getId());
        QueryWrapper<Visa> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("id", visaHandleReq.getId());
        Visa visa = visaMapper.selectOne(wrapper1);
        if (visa != null) {
            visaOrder.setVisaTypeId(visa.getVisaTypeId());
            visaOrder.setVisaType(visa.getVisaType());
        }
        // 单价
        visaOrder.setSinglePrice(visaHandleReq.getSinglePrice());
        // 数量
        visaOrder.setTotalNum(visaHandleReq.getTotalNum());
        //todo   上线去掉
        UserDTO userDTO = null;
        try {
            userDTO = iSysUserService.loadUserByParam(user.getId(), 1);
            if (userDTO == null) {
                throw new BusinessException(SystemError.SYS_502);
            }
            // 生成订单号 V+部門代碼+員工編號+年後2位+月日4位+3位隨機數字
            if (userDTO.getDeptId() != null) {
                SysDepartmentDTO sysDepartmentDTO = sysDepartmentService.queryOne(userDTO.getDeptId());
                if (sysDepartmentDTO != null) {
                    if (sysDepartmentDTO.getDeptCode() != null) {
                        userDTO.setDeptCode(sysDepartmentDTO.getDeptCode());
                    }
                }
            }
            String orderNumber = "V" + userDTO.getDeptCode() + userDTO.getEmployeeNumber() + DateUtil.fmtNum(LocalDate.now()) + RandomUtil.randomNumbers(3);
            // 订单编码
            visaOrder.setOrderNumber(orderNumber);
        } catch (Exception e) {
            throw new BusinessException(SystemError.SYS_502);
        }
        // 预订状态
        visaOrder.setBookingStatus(0);
        // 取消状态
        visaOrder.setCancelStatus(0);
        // 支付状态
        visaOrder.setStatus(1);
        // 联系人邮箱
        visaOrder.setContactEmail(visaHandleReq.getContactEmail());
        // 创建时间
        visaOrder.setGmtCreate(LocalDateTime.now());
        // 联系人手机号
        visaOrder.setContactMobile(visaHandleReq.getContactMobile());
        // 联系人手机区号
        visaOrder.setContactMobileAreaCode(visaHandleReq.getContactMobileAreaCode());
        // 联系人姓名
        visaOrder.setContactName(visaHandleReq.getContactName());
        // 备注
        visaOrder.setRemark(visaHandleReq.getRemark());
        // 收款方式
        visaOrder.setPayWay(visaHandleReq.getPayWay());
        // 总数量
        visaOrder.setTotalNum(visaHandleReq.getTotalNum());
        // 总金额
        visaOrder.setTotalAmount(visaHandleReq.getTotalAmount());
        // 付款到期时间
        visaOrder.setPayExpireDate(LocalDateTime.now().plusMinutes(30));
        // 办理地点
        visaOrder.setProcessingPlace(visaHandleReq.getProcessingPlace());
        // 办理地点id
        visaOrder.setProcessingPlaceId(visaHandleReq.getProcessingPlaceId());
        // 委托种类id
        visaOrder.setTypeId(visaHandleReq.getTypeId());
        if (visaHandleReq.getProcessingDate() != null) {
            // 办理日期
            visaOrder.setProcessingDate(visaHandleReq.getProcessingDate());
        }
        // 旅客信息
        List<VisaOrderTouristListReq> visaOrderTouristListReqList = visaHandleReq.getVisaOrderTouristListReqs();
        List<VisaOrderTourist> visaOrderTouristList = new ArrayList<>();
        if (null != visaOrderTouristListReqList) {
            // 遍历旅客信息
            for (VisaOrderTouristListReq visaOrderTouristListReq : visaOrderTouristListReqList) {
                // 旅客证件列表
                List<VisaTouristListReq> listReqs = visaOrderTouristListReq.getVisaTouristListReqs();
                net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(listReqs);
                Long tourisId = SnowflakeIdWorker.nextId();
                if (null != listReqs && listReqs.size() > 0) {
//                for (int i = 0; i < listReqs.size(); i++) {
                    VisaOrderTourist visaOrderTourist = new VisaOrderTourist();
                    // 证件json数组
                    visaOrderTourist.setCertificatesJson(jsonArray.toString());
                    // 证件类型
                    visaOrderTourist.setCertificatesType(listReqs.get(0).getCertificatesType());
                    // 证件号码
                    visaOrderTourist.setCertificatesNumber(listReqs.get(0).getCertificatesNumber());
                    // 创建人
                    visaOrderTourist.setCreateId(user.getId());
                    // 旅客id
                    visaOrderTourist.setId(tourisId);
                    // 旅客性别
                    visaOrderTourist.setGender(Integer.parseInt(visaOrderTouristListReq.getGender()));
                    // 订单id
                    visaOrderTourist.setOrderId(id);
                    // 创建时间
                    visaOrderTourist.setGmtCreate(LocalDateTime.now());
                    // 旅客姓
                    visaOrderTourist.setSurname(visaOrderTouristListReq.getSurname());
                    // 旅客生日
                    visaOrderTourist.setBirthday(visaOrderTouristListReq.getBirthday());
                    // 删除标识
                    visaOrderTourist.setIsDeleted(0);
                    visaOrderTouristList.add(visaOrderTourist);
                    VisaManage visaManage = new VisaManage();
                    visaManage.setCollectionStatus(1);
                    visaManage.setTouristId(tourisId);
                    visaManage.setCreateId(user.getId());
                    visaManage.setGmtCreate(LocalDateTime.now());
                    visaManageMapper.insert(visaManage);
                    tourisId = SnowflakeIdWorker.nextId();
//                }
                }
            }
        }
        visaOrderTouristMapper.insertBatchSomeColumn(visaOrderTouristList);
        visaOrderMapper.insert(visaOrder);

        /**
         * 新增签证成功，执行定时任务，如果未付款则取消
         */
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", id);
        long delayMS = 10000 * 18;
        log.info("【签证订单-提交订单】提交订单成功，启动定时任务:{},appName:{},time:{}", domain, appName, delayMS);
        try {
            OhMyClient taskClient = new OhMyClient(domain, appName, password);
            ResultDTO<Long> resultTask = taskClient.runJob(jobId, jsonObject.toJSONString(), delayMS);

            if (resultTask.isSuccess()) {
                // 任务执行成功,过期时间*2是防止任务启动时redis数据已过期
                redisTemplate.opsForValue().set(RedisConstants.ORDER_INSTANCELD_KEY + id, resultTask.getData(), delayMS * 2, TimeUnit.MILLISECONDS);
            }
        } catch (Exception e) {
            log.error("【签证订单-提交订单】提交订单失败，启动定时任务失败", e);
            throw new BusinessException(SystemError.VISA_ORDER_20015);
        }
        return id;
    }

    @Override
    public Result updateStatus() {
        QueryWrapper<VisaOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("is_deleted", 0);
        List<VisaOrder> visaOrderList = visaOrderMapper.selectList(wrapper);
        for (VisaOrder visaOrder : visaOrderList) {
            LocalDateTime date = visaOrder.getPayExpireDate();
            Integer status = visaOrder.getStatus();
            LocalDateTime nowDate = LocalDateTime.now();
            Duration duration = Duration.between(date, nowDate);
            long minuts = duration.toMinutes();
            if (status == 0 && minuts > 30) {
                visaOrder.setStatus(3);
                visaOrder.setGmtModified(LocalDateTime.now());
                int update = visaOrderMapper.updateById(visaOrder);
                if (update <= 0) {
                    throw new BusinessException(SystemError.SYS_437);
                }
            }
        }
        return Result.success();
    }

    @Override
//    @GlobalTransactional(rollbackFor = Exception.class)
    public Result visaOrderCollection(Visa0rderCollectionDetailReq rderCollectionDetailReq, TokenUser user) {
        QueryWrapper<VisaOrder> visaOrderQueryWrapper = new QueryWrapper<>();
        visaOrderQueryWrapper.eq("id", rderCollectionDetailReq.getOrderId());
        visaOrderQueryWrapper.eq("is_deleted", 0);
        // 获取签证订单
        VisaOrder visaOrder = visaOrderMapper.selectOne(visaOrderQueryWrapper);
        if (visaOrder == null) {
            // 订单不存在
            return Result.failed(SystemError.VISA_ORDER_25005);
        }
        LocalDateTime nowLocalDateTime = LocalDateTime.now();
        // todo 支付超时，未做
        UserDTO userDTO = iSysUserService.queryCacheUser(user.getId());
        visaOrder.setGmtCreate(nowLocalDateTime);
        visaOrder.setModifiedId(userDTO.getId());
        visaOrder.setStatus(OrderPaymentStatus.ALREADY_PAYMENT.getCode());

        // 收款明细获取
        List<Visa0rderCollectionListReq> visa0rderCollectionListReqList = rderCollectionDetailReq.getVisa0rderCollectionListReqList();
        if (CollectionUtils.isNotEmpty(visa0rderCollectionListReqList)) {

            // 获取签证旅客信息
            QueryWrapper<VisaOrderTourist> wrapper = new QueryWrapper<>();
            wrapper.eq("order_id", visaOrder.getId());
            List<VisaOrderTourist> visaOrderTourists = visaOrderTouristMapper.selectList(wrapper);

            // 获取签证产品信息
            QueryWrapper<VisaProduct> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", visaOrder.getProductId());
            VisaProduct visaProduct = visaProductMapper.selectOne(queryWrapper);
            if (visaProduct == null) {
                return Result.failed(SystemError.VISA_ORDER_25012);
            }

            // 获取签证资源
            QueryWrapper<Visa> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("id", visaProduct.getVisaId());
            Visa visa = visaMapper.selectOne(wrapper1);

            if (visa == null) {
                return Result.failed(SystemError.VISA_ORDER_25014);
            }
            // 获取签证类型
            QueryWrapper<VisaType> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("visa_id", visa.getId());
            List<VisaType> visaTypeList = visaTypeMapper.selectList(wrapper2);
            if (CollectionUtils.isNotEmpty(visaTypeList)) {

                List<VisaOrderCollection> collectionList = new ArrayList<>();
                for (Visa0rderCollectionListReq visa0rderCollectionListReq : visa0rderCollectionListReqList) {
                    VisaOrderCollection visaOrderCollection = new VisaOrderCollection();
                    //生成收款单号,SKD+年後2位+月日4位+時分秒6位+2位隨機數字
                    String collectionNumber = "SKD" + DateUtil.fmtNum(LocalDate.now()) + RandomUtil.randomNumbers(2);
                    visaOrderCollection = EntityUtil.copy(visa0rderCollectionListReq, VisaOrderCollection.class);
                    visaOrderCollection.setCollectionNumber(collectionNumber);
                    visaOrderCollection.setCreateId(user.getId());
                    visaOrderCollection.setStatus(OrderPaymentStatus.ALREADY_PAYMENT.getCode());
                    visaOrderCollection.setOrderId(visaOrder.getId());
                    visaOrderCollection.setCreateId(userDTO.getId());
                    visaOrderCollection.setCollectionAmount(visa0rderCollectionListReq.getCollectionAmount());
                    visaOrderCollection.setGmtCreate(LocalDateTime.now());
                    visaOrderCollection.setId(SnowflakeIdWorker.nextId());
                    visaOrderCollection.setCurrencyId(visa0rderCollectionListReq.getCurrencyId());
                    visaOrderCollection.setCurrency(visa0rderCollectionListReq.getCurrency());
                    collectionList.add(visaOrderCollection);
                    visaOrderCollectionMapper.insert(visaOrderCollection);
                }
                /**
                 * 自由行预订-签证新增(自由行付款专用)
                 */
                generatorSupplierBooking(visaProduct, visaOrderTourists, visaOrder, userDTO.getId(), visa, visaTypeList.get(0));

                /**
                 * 生成财务收款记录
                 */
                generatorFinance(userDTO.getId(), visaOrder, visa, collectionList);
                visaOrder.setBookingStatus(4);
                visaOrder.setCancelStatus(0);
                visaOrder.setStatus(2);
                visaOrderMapper.updateById(visaOrder);
                return Result.success();
            }
        }
        return Result.failed(SystemError.TOUR_ORDER_30011);
    }

    private void generatorSupplierBooking(VisaProduct visaProduct, List<VisaOrderTourist> visaOrderTourists, VisaOrder visaOrder, Long userId, Visa visa, VisaType visaType) {
        SupplierOrderSystemVisaAddReq supplierOrderSystemVisaAddReq = new SupplierOrderSystemVisaAddReq();
        // 生成供应预订单
        UserDTO chargeUser = iSysUserService.queryCacheUser(userId);
        supplierOrderSystemVisaAddReq.setSupplierId(visaType.getSupplierId()); // 供应商ID
        supplierOrderSystemVisaAddReq.setSupplierName(visaType.getSupplierName());
        // todo 办理时内部挂账待完成
        supplierOrderSystemVisaAddReq.setSupplierOrderType("1"); //供应商订单类型
        supplierOrderSystemVisaAddReq.setOriginalSaleNumber(null);
        supplierOrderSystemVisaAddReq.setBusinessType(SystemBusinessType.VISA.getCode());
        supplierOrderSystemVisaAddReq.setSaleType(SalesMethod.SINGLE_SALE.getCode());
        supplierOrderSystemVisaAddReq.setReserveTypeId(SupplierReserveTypeEnum.VISA.getId());
        supplierOrderSystemVisaAddReq.setProductType(ProductType.MANUAL_ENTRY.getCode());
        supplierOrderSystemVisaAddReq.setDepartmentId(chargeUser.getDeptId()); // 资源所属部门ID
        supplierOrderSystemVisaAddReq.setDepartment(chargeUser.getDept());
        supplierOrderSystemVisaAddReq.setSaleNumber(visaOrder.getOrderNumber());
        supplierOrderSystemVisaAddReq.setProductNumber(visa.getId().toString());
        supplierOrderSystemVisaAddReq.setProductName(visa.getName());
        supplierOrderSystemVisaAddReq.setTotalFee(visaType.getCostAmount());
        supplierOrderSystemVisaAddReq.setCurrencyId(visaType.getCurrencyId());
        supplierOrderSystemVisaAddReq.setCurrency(visaType.getCurrency());

        // todo 委托种类的成本金额
        supplierOrderSystemVisaAddReq.setPayableAmount(visaType.getCostAmount());
        // todo 前端给的凭证
        supplierOrderSystemVisaAddReq.setFilesJson(null);
        supplierOrderSystemVisaAddReq.setConfirmStatus(OrderSubscribeStatus.CONFIRM.getCode());

        // 构建供应商预订-签证信息
        List<SupplierSystemOrderVisaAddReq> visaAddReqList = new ArrayList<>();
        SupplierSystemOrderVisaAddReq visaAddReq = new SupplierSystemOrderVisaAddReq();
        visaAddReq.setOrderId(visaOrder.getId());
        visaAddReq.setCustomerRemark("");
        ArrayList<SupplierSystemOrderVisaDetailAddReq> detailAddReqList = new ArrayList<>();
        SupplierSystemOrderVisaDetailAddReq req = new SupplierSystemOrderVisaDetailAddReq();
        // 国家名称
        req.setCountryName(visa.getCountryName());
        // 国家id
        req.setCountryId(visa.getCountryId());
        // 签证类型id
        req.setVisaId(visa.getId());
        // 签证名称
        req.setVisaName(visa.getName());
        // 有效次数
        req.setEffectiveFrequency(visa.getVaildTimes());
        // 委托种类id
        req.setEntrustTypeId(visaType.getTypeId());
        // 委托种类名称
        req.setEntrustTypeName(visaType.getTypeName());
        if (visaOrderTourists.size() > 0 && visaOrderTourists != null) {
            // 旅客数量
            req.setNumber(visaOrderTourists.size());
            for (VisaOrderTourist orderTourist : visaOrderTourists) {
                // 旅客名称
                if (req.getPassengerName() == null) {
                    req.setPassengerName("");
                }
                req.setPassengerName(req.getPassengerName().concat("," + orderTourist.getSurname() + orderTourist.getName()));
            }
        }

        BigDecimal price = new BigDecimal("0");
        // 单价
        if (visaProduct.getAdjustType() == 1) {
            price.add(visaType.getCostAmount());
            req.setPrice(price);
        } else if (visaProduct.getAdjustType() == 2) {
            req.setPrice(visaType.getCostAmount().multiply(new BigDecimal(visaProduct.getPercent())).divide(new BigDecimal("100")));
        }
        detailAddReqList.add(req);
        visaAddReq.setSupplierSystemOrderVisaDetailAddReqList(detailAddReqList);
        visaAddReqList.add(visaAddReq);
        supplierOrderSystemVisaAddReq.setSupplierSystemOrderVisaAddReqList(visaAddReqList);
        supplierOrderService.addSystemVisa(supplierOrderSystemVisaAddReq, userId);
    }

    private void generatorFinance(Long userId, VisaOrder visaOrder, Visa visa, List<VisaOrderCollection> visaOrderCollections) {
        List<BillAddCollectionReq> billAddCollectionReqs = new ArrayList<>();
        for (VisaOrderCollection visaOrderCollection : visaOrderCollections) {
            List<FileJson> fileJsons = JSON.parseArray(visaOrderCollection.getCollectionCertificateJson(), FileJson.class);
            UserDTO userDTOTemp = iSysUserService.queryCacheUser(visaOrder.getCreateId());
            BillAddCollectionReq billAddCollectionReq = new BillAddCollectionReq();
            billAddCollectionReqs.add(billAddCollectionReq);
            billAddCollectionReq.setBillNumber(visaOrderCollection.getCollectionNumber());
            billAddCollectionReq.setBusinessType(SystemBusinessType.VISA.getCode());
            billAddCollectionReq.setCollectionWayId(visaOrderCollection.getCollectionWayId());
            billAddCollectionReq.setCollectionWayName(visaOrderCollection.getCollectionWay());
            billAddCollectionReq.setCollectionTypeId(CollectionTypeIdCode.FULL.getCode());
            billAddCollectionReq.setCollectionTypeName(CollectionTypeIdCode.FULL.getMsg());
            billAddCollectionReq.setCollectionAmount(visaOrderCollection.getCollectionAmount());
            billAddCollectionReq.setCurrencyId(visaOrderCollection.getCurrencyId());
            billAddCollectionReq.setCurrencyName(visaOrderCollection.getCurrency());
            MainDataCurrencyUpdateStatusReq dataCurrencyUpdateStatusReq = new MainDataCurrencyUpdateStatusReq();
            dataCurrencyUpdateStatusReq.setId(visaOrderCollection.getCurrencyId());
            Result<MainDataCurrencyQueryDTO> query = iMainDataCurrencyService.query(dataCurrencyUpdateStatusReq);
            billAddCollectionReq.setExchangeRate(query.getData().getMarketExchangeRate().doubleValue());
//            billAddCollectionReq.setExchangeRate(new Double(1));
            billAddCollectionReq.setCollectionTime(visaOrderCollection.getGmtCreate());
            billAddCollectionReq.setCollectionVoucherJsonList(fileJsons); // 收款凭证
            billAddCollectionReq.setSaleOrderNumber(visaOrder.getOrderNumber());
            billAddCollectionReq.setSaleOrderId(visaOrder.getId());
            // todo 产品id和编号缺少两个备注
            billAddCollectionReq.setProductId(Arrays.asList(visa.getId()));
            billAddCollectionReq.setProductNumber(visa.getId().toString());
            billAddCollectionReq.setProductName(visa.getName());
            billAddCollectionReq.setResourceInfo(Arrays.asList(visa.getName()));
            billAddCollectionReq.setSaleUserId(userDTOTemp.getId());
            billAddCollectionReq.setSaleUserName(userDTOTemp.getFullName());
            billAddCollectionReq.setSaleDeptId(userDTOTemp.getDeptId());
            billAddCollectionReq.setUserId(userId);
            log.info("【签证订单】生成财务收款记录, req:{}", JSON.toJSONString(billAddCollectionReqs));
            financeBillService.addCollection(billAddCollectionReqs);
        }
    }

    @Override
    public Result<Long> cancelVisaOrder(Visa0rderCancelReq visa0rderCancelReq, TokenUser tokenUser) {
        VisaOrder visaOrder = visaOrderMapper.selectById(visa0rderCancelReq.getOrderId());
//        visaOrder = EntityUtil.copy(visa0rderCancelReq, VisaOrder.class);
        visaOrder.setCancelStatus(0);
        visaOrder.setBookingStatus(0);
        visaOrder.setStatus(3);
        visaOrder.setModifiedId(tokenUser.getId());
        visaOrder.setGmtModified(LocalDateTime.now());
        visaOrderMapper.updateById(visaOrder);
        return Result.success(visaOrder.getId());
    }

    @DubboReference
    private ISysApprovalService sysApprovalService;

    @Transactional
    @Override
    public Result<Long> cancelVisaOrderRefund(Visa0rderRefundDetailReq visa0rderRefundDetailReq, TokenUser
            tokenUser) {
        VisaOrder visaOrder = visaOrderMapper.selectById(visa0rderRefundDetailReq.getOrderId());
        // 訂單判斷存在
        if (visaOrder == null) {
            throw new BusinessException(SystemError.VISA_ORDER_25005);
        }
        visaOrder.setRemark(visa0rderRefundDetailReq.getRemark());
        visaOrder.setCancelReason(visa0rderRefundDetailReq.getCancelReason());
        visaOrder.setGmtModified(LocalDateTime.now());
        visaOrder.setModifiedId(tokenUser.getId());
        // 已付款
        if (visaOrder.getStatus() == OrderPaymentStatus.ALREADY_PAYMENT.getCode()) {
            // 取消狀態
            if (visaOrder.getCancelStatus() != 0) {
                //正在取消订单，请勿重复提交
                throw new BusinessException(SystemError.VISA_ORDER_25004);
            }

            // 獲取退款明細
            List<Visa0rderRefundListReq> visa0rderRefundListReqList = visa0rderRefundDetailReq.getVisa0rderRefundListReqList();
            if (CollectionUtils.isEmpty(visa0rderRefundListReqList)) {
                throw new BusinessException(SystemError.VISA_ORDER_25006);
            }
            Integer code = 0;
            switch (visaOrder.getBookingStatus()) {
                // 预订状态为待确认
                case 4:
                    // 预订状态为确认成功
                case 5:
                    // 预订状态为确认失败
                case 6:
                    // 取消狀態變化
                    code = ApprovalStatus.RECALL.getCode();
                    break;
                default:
                    break;
            }
            switch (visaOrder.getBookingStatus()) {
                case 4:
                    // 预订状态为待确认
                    visaOrder.setBookingStatus(6);
                    break;
                case 5:
                    // 预订状态为确认成功
                    visaOrder.setBookingStatus(5);
                    break;
                case 6:
                    // 预订状态为确认取消
                    visaOrder.setBookingStatus(5);
                    break;
                default:
                    break;
            }

            visaOrder.setCancelStatus(code);

            // 獲取旅客信息
            QueryWrapper<VisaOrderTourist> visaOrderTouristQueryWrapper = new QueryWrapper<>();
            visaOrderTouristQueryWrapper.eq("order_id", visaOrder.getId());
            visaOrderTouristQueryWrapper.eq("is_deleted", 0);
            List<VisaOrderTourist> visaOrderTouristList = visaOrderTouristMapper.selectList(visaOrderTouristQueryWrapper);
            VisaOrderTourist visaOrderTourist = null;

            if (CollectionUtils.isEmpty(visaOrderTouristList)) {
                // 旅客列表不存在
                throw new BusinessException(SystemError.VISA_ORDER_25007);
            } else {
                visaOrderTourist = visaOrderTouristList.get(0);
            }

            for (Visa0rderRefundListReq visa0rderRefundListReq : visa0rderRefundListReqList) {
                // 簽證退款記錄存儲
                VisaOrderRefund visaOrderRefund = new VisaOrderRefund();
                visaOrderRefund = EntityUtil.copy(visa0rderRefundListReq, VisaOrderRefund.class);
                Visa0rderRefundWayReq visa0rderRefundWayReq = visa0rderRefundListReq.getVisa0rderRefundWayReq();
                visaOrderRefund.setRefundWayId(Long.parseLong(visa0rderRefundWayReq.getValue()));
                visaOrderRefund.setRefundWay(visa0rderRefundWayReq.getLabel());
                if (visaOrderTourist != null) {
                    visaOrderRefund.setTouristId(visaOrderTourist.getId());
                    visaOrderRefund.setTouristName(visaOrderTourist.getName());
                }
                RefundAmountReq refundAmountReq = visa0rderRefundListReq.getRefundAmountReq();
                BigDecimal crmExchangeRate = getCrmExchangeRateByName(refundAmountReq.getCurrencyName());
                BigDecimal refundAmount = refundAmountReq.getCollectionAmount().multiply(crmExchangeRate);
                visaOrderRefund.setRefundAmount(refundAmount);
                visaOrderRefund.setId(SnowflakeIdWorker.nextId());
                visaOrderRefund.setOrderId(visaOrder.getId());
                //退款单号 TKD+年後2位+月日4位+時分秒6位+2位隨機數字
                String refundNumber = "TKD" + DateUtil.fmtNum(LocalDate.now()) + RandomUtil.randomNumbers(2);
                visaOrderRefund.setRefundNumber(refundNumber);
                visaOrderRefund.setRemark(visa0rderRefundDetailReq.getRemark());
                visaOrderRefund.setRefundReason(visa0rderRefundDetailReq.getCancelReason());
                visaOrderRefund.setCreateId(tokenUser.getId());
                visaOrderRefund.setGmtCreate(LocalDateTime.now());
                visaOrderRefundMapper.insert(visaOrderRefund);

            }

            // 發起業務審批電子流
            log.info("【簽證订单】submit cancel order approval, business type:{}, approval type:{}", SystemBusinessType.VISA, SysApprovalType.CANCEL_VISA);
            Result<ApprovalStartDTO> approvalStartDTOResult = sysApprovalService.start(SystemBusinessType.VISA.getCode(), SysApprovalType.CANCEL_VISA.getCode(), Long.parseLong(visa0rderRefundDetailReq.getOrderId()), tokenUser.getId(), null, null);
            if (!approvalStartDTOResult.isSuccess()) {
                SystemError defined = SystemError.getDefined(approvalStartDTOResult.getCode());
                throw new BusinessException(defined);
            }
            visaOrderMapper.updateById(visaOrder);
        }
        return Result.success(visaOrder.getId());
    }

    /**
     * 根据币种名称获取汇率
     *
     * @param currencySy
     * @return
     */
    private BigDecimal getCrmExchangeRateByName(String currencySy) {
        MainDataCurrencyListReq mainDataCurrencyListReq = new MainDataCurrencyListReq();
        mainDataCurrencyListReq.setName(currencySy);
        mainDataCurrencyListReq.setStatus(0);
        PageResponse<MainDataCurrencyListDTO> list = iMainDataCurrencyService.list(mainDataCurrencyListReq);
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(list.getRecords())) {
            throw new BusinessException(SystemError.AIREXPRESS_ORDER_60003);
        }
        return list.getRecords().get(0).getCrmExchangeRate();
    }

    @Override
    public Result notice(Visa0rderNoticeReq visa0rderNoticeReq) {
        return Result.success();
    }

    @DubboReference
    IFinanceBillService financeBillService;

    @Override
    public Result approval(VisaOrderRefundApprovalReq visaOrderRefundApprovalReq) {
        if (visaOrderRefundApprovalReq.getApprovalId() == null) {
            return Result.failed(SystemError.SYS_402);
        }
        if (!ApprovalStatus.isCheckStatus(visaOrderRefundApprovalReq.getApprovalStatus())) {
            return Result.failed(SystemError.SYS_402);
        }
        QueryWrapper<VisaOrder> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(VisaOrder::getId, visaOrderRefundApprovalReq.getBusinessId());
        wrapper.lambda().eq(VisaOrder::getIsDeleted, IsDeletedCode.NO);
        VisaOrder visaOrder = visaOrderMapper.selectOne(wrapper);
        if (visaOrder == null) {
            return Result.failed(SystemError.VISA_ORDER_25005);
        }
        if (!ApprovalStatus.REVIEWING.getCode().equals(visaOrder.getCancelStatus())) {
            return Result.failed(SystemError.VISA_ORDER_25008);
        }

        // 退款记录查询
        QueryWrapper<VisaOrderRefund> orderRefundQueryWrapper = new QueryWrapper<>();
        orderRefundQueryWrapper.lambda().eq(VisaOrderRefund::getOrderId, visaOrderRefundApprovalReq.getBusinessId());
        orderRefundQueryWrapper.lambda().eq(VisaOrderRefund::getIsDeleted, IsDeletedCode.NO);
        List<VisaOrderRefund> visaOrderRefunds = visaOrderRefundMapper.selectList(orderRefundQueryWrapper);
        if (CollectionUtils.isEmpty(visaOrderRefunds)) {
            return Result.failed(SystemError.VISA_ORDER_25009);
        }
        LocalDateTime nowLocalDateTime = LocalDateTime.now();
        log.info("【签证订单-退款】approval status:{}", visaOrderRefundApprovalReq.getApprovalStatus());
        // 审批通过
        if (ApprovalStatus.REVIEW_YES.getCode() == visaOrderRefundApprovalReq.getApprovalStatus()) {
            if (CollectionUtils.isEmpty(visaOrderRefundApprovalReq.getVisaOrderRefundListReqList())) {
                //  退款金额为空
                throw new BusinessException(SystemError.VISA_ORDER_25010);
            }
            // 审批通过
            visaOrder.setCancelStatus(ApprovalStatus.REVIEW_YES.getCode());

            // 校验审批金额
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (VisaOrderRefund visaOrderRefund : visaOrderRefunds) {
                visaOrderRefund.setStatus(ApprovalStatus.REVIEW_YES.getCode());
                for (Visa0rderRefundListReq visa0rderRefundListReq : visaOrderRefundApprovalReq.getVisaOrderRefundListReqList()) {
                    if (Objects.equals(visa0rderRefundListReq.getId(), visaOrderRefund.getId())) {
                        // 收款金额
                        RefundAmountReq amountReq = visa0rderRefundListReq.getRefundAmountReq();
                        // 金额计算
                        totalAmount = totalAmount.add(amountReq.getCollectionAmount());
                        break;
                    }
                }
            }

            /**
             * 新增财务退款记录
             */
            List<BillAddRefundReq> billAddRefundReqs = new ArrayList<>();
            for (VisaOrderRefund visaOrderRefund : visaOrderRefunds) {
                List<Long> productIds = new ArrayList<>();
                List<String> resources = new ArrayList<>();

                BillAddRefundReq billAddRefundReq = new BillAddRefundReq();
                // 退款单号
                billAddRefundReq.setBillNumber(visaOrderRefund.getOrderId().toString());
                // 业务类型
                billAddRefundReq.setBusinessType(SystemBusinessType.VISA.getCode());
                // 退款金额
                billAddRefundReq.setCollectionAmount(totalAmount);

                QueryWrapper<VisaProduct> productQueryWrapper = new QueryWrapper<>();
                productQueryWrapper.eq("id", visaOrder.getProductId());
                VisaProduct visaProduct = visaProductMapper.selectOne(productQueryWrapper);
                if (visaProduct != null) {
                    QueryWrapper<VisaType> typeQueryWrapper = new QueryWrapper<>();
                    typeQueryWrapper.eq("visa_id", visaProduct.getVisaId());
                    VisaType visaType = visaTypeMapper.selectOne(typeQueryWrapper);
                    if (visaType != null) {
                        // 币种ID
                        billAddRefundReq.setCurrencyId(visaType.getCurrencyId());
                        // 币种名称
                        billAddRefundReq.setCurrencyName(visaType.getCurrency());
                    }
                    QueryWrapper<Visa> visaQueryWrapper = new QueryWrapper<>();
                    visaQueryWrapper.eq("id", visaProduct.getVisaId());
                    Visa visa = visaMapper.selectOne(visaQueryWrapper);
                    if (visa != null) {
                        productIds.add(visa.getId());
                        resources.add(visa.getName());
                        // 产品名称
                        billAddRefundReq.setProductName(visa.getName());
                    }
                }
                // 销售单号
                billAddRefundReq.setSaleOrderNumber(visaOrder.getOrderNumber());
                // 销售ID
                billAddRefundReq.setSaleOrderId(visaOrder.getId());
                // 产品ID
                billAddRefundReq.setProductId(productIds);
                // 产品编号
                // 资源信息列表
                billAddRefundReq.setResourceInfo(resources);
                // 联系电话
                billAddRefundReq.setContactMobile(visaOrder.getContactMobile());
                // 退款备注
                billAddRefundReq.setRefundRemark(visaOrderRefund.getRemark());
                // 退款方式
                billAddRefundReq.setRefundType(visaOrderRefund.getRefundWay());
                // 汇率
                // 旅客姓名
                billAddRefundReq.setTouristName(visaOrderRefund.getTouristName());
                // 退款时间 todo 待确认
                billAddRefundReq.setRefundTime(nowLocalDateTime);
                // 退款备注
                billAddRefundReq.setRefundRemark(visaOrderRefund.getRefundReason());
                // 用户id
                billAddRefundReq.setUserId(visaOrderRefundApprovalReq.getUserId());
                billAddRefundReqs.add(billAddRefundReq);
            }
            financeBillService.addRefund(billAddRefundReqs);
        } else if (ApprovalStatus.REVIEW_NO.getCode() == visaOrder.getCancelStatus()) {
            // 审批不通过
            visaOrder.setCancelStatus(ApprovalStatus.REVIEW_NO.getCode());
            for (VisaOrderRefund visaOrderRefund : visaOrderRefunds) {
                visaOrderRefund.setStatus(ApprovalStatus.REVIEW_NO.getCode());
            }
        } else {
            // 撤回
            visaOrder.setCancelStatus(0);
            for (VisaOrderRefund visaOrderRefund : visaOrderRefunds) {
                visaOrderRefund.setStatus(0);
                visaOrderRefund.setIsDeleted(IsDeletedCode.YES.getCode());
            }
        }
        /**
         * 审批
         */
        Result<ApprovalCheckDTO> check = sysApprovalService.check(visaOrderRefundApprovalReq.getApprovalId(), visaOrderRefundApprovalReq.getUserId(), visaOrderRefundApprovalReq.getApprovalStatus(), visaOrderRefundApprovalReq.getComments());
        if (!check.isSuccess()) {
            SystemError systemError = SystemError.getDefined(check.getCode());
            return Result.failed(systemError);
        }
        if (check.getData() == null || !check.getData().getIsFinish()) {
            return Result.success();
        }
        for (VisaOrderRefund visaOrderRefund : visaOrderRefunds) {
            visaOrderRefund.setModifiedId(visaOrderRefundApprovalReq.getUserId());
            visaOrderRefund.setGmtModified(nowLocalDateTime);
            visaOrderRefundMapper.updateById(visaOrderRefund);
        }
        visaOrder.setModifiedId(visaOrderRefundApprovalReq.getUserId());
        visaOrder.setGmtModified(nowLocalDateTime);
        visaOrderMapper.updateById(visaOrder);
        return Result.success();
    }
}
